-module(simple_server).
-export([start_nano_server/0,nano_client_eval/1]).

start_nano_server() ->
    {ok, Listen} = gen_tcp:listen(5555, [binary, {packet, 2},
                                        {reuseaddr, true},
                                        {active, true}]),
    {ok, Socket} = gen_tcp:accept(Listen),
    Table = ets:new(?MODULE,[set]),
    gen_tcp:close(Listen),
    loop(Socket,Table),
    ets:delete(Table).

loop(Socket,Table) ->
    receive
        {tcp, Socket, Bin} ->
            io:format("Server received binary = ~p~n" ,[Bin]),
            Str = binary_to_term(Bin),
            io:format("Server (unpacked) ~p~n" ,[Str]),
            Reply = handle_cmd(Str,Table),
            io:format("Server replying = ~p~n" ,[Reply]),
            gen_tcp:send(Socket, term_to_binary(Reply)),
            loop(Socket,Table);
        {tcp_closed, Socket} ->
            io:format("Server socket closed~n" )
    end.

handle_cmd({set,Name,Value},Table) ->
    ets:insert(Table,{Name,Value}),
    ok;

handle_cmd({get,Name},Table) ->
    case ets:lookup(Table,Name) of
        []       ->
            {error,notfound};
        [Value]  ->
            {ok,Value}
    end;

handle_cmd({delete,Name},Table) ->
    ets:delete(Table,Name),
    ok;

handle_cmd(Cmd,_Table) ->
    {error, Cmd}.


nano_client_eval(Str) ->
    {ok, Socket} =
        gen_tcp:connect("localhost" , 5555,
                         [binary, {packet, 2}]),
    ok = gen_tcp:send(Socket, term_to_binary(Str)),
    receive
        {tcp,Socket,Bin} ->
            io:format("Client received binary = ~p~n" ,[Bin]),
            Val = binary_to_term(Bin),
            io:format("Client result = ~p~n" ,[Val]),
            gen_tcp:close(Socket)
    end.